<?php

/**
 * DB singleton
 * 
 */

class DB {
  private static $db = null;
  
  private function __construct(){
  }

  /**
 * @return mysqli_log
 */
  
  public static function getDB() {
    if(self::$db == null){
      self::$db = new mysqli_log(DB_IP, DB_USER, DB_PASS, DB_NAME);
      /* check connection */
      if (mysqli_connect_errno()) {
         throw new Exception( "Connect failed: \n" . mysqli_connect_error(), 
                              mysqli_connect_errno());
      }
    }
    return self::$db;
  }
}
class mysqli_log extends mysqli {
  
  public function query($query, $resultmode=MYSQLI_STORE_RESULT) {
    $res = parent::query($query, $resultmode);
    if(Log::medium($this->error)) {
      throw new DBException($this->error);
    }
    return $res;
  }
  
  public function prepare($query) {
    $stmt = parent::prepare($query);
    if(Log::medium($this->error)) {
      throw new DBException($this->error);
    }
    return $stmt;
  }
  
  
}

class mysqli_stmt_log extends mysqli_stmt {
  
  public function execute() {
    if(!parent::execute()) {
      if(Log::medium($this->error)) {
        $error = $this->error;
        $this->close();
        throw new DBException($error);
      }
    }
    return true;
  }
}

class DBException extends Exception {
  
}
?>
